package zhanglinwei.cryptotools.core.resolver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CryptoablePropertyResolverFactory {
    private static final Logger log = LoggerFactory.getLogger(CryptoablePropertyResolverFactory.class);
    private final ApplicationContext applicationContext;
    private static Map<String, CryptoablePropertyResolver> resolverMap;

    public CryptoablePropertyResolverFactory(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        init();
    }

    private void init() {
        Map<String, CryptoablePropertyResolver> propertyResolverMap = applicationContext.getBeansOfType(CryptoablePropertyResolver.class);
        if (!propertyResolverMap.isEmpty()) {
            resolverMap = propertyResolverMap.values().stream()
                    .collect(Collectors.toMap(CryptoablePropertyResolver::algorithm, Function.identity()));
        }
    }

    public CryptoablePropertyResolver getPropertyResolver(String algorithm) {
        CryptoablePropertyResolver cryptoablePropertyResolver = resolverMap.get(algorithm);
        if (cryptoablePropertyResolver == null) {
            throw new IllegalArgumentException(String.format("【%s】 algorithm resolver not found", algorithm));
        }
        return cryptoablePropertyResolver;
    }

}
